#include "graphdata.h"
#include <limits>

namespace Graph
{

GraphData::GraphData(QCPGraph *graph, QListWidgetItem *item, const int &coloumn, QVector<double> * time, const GraphSettings &graphSettings) :
    graph(graph), time(time), widgetItem(item)
{
    graph->setPen(QPen(graphSettings.color));
    graph->setVisible(graphSettings.visible);
    coloumnFile = coloumn;

    if (graphSettings.visible)
    {
        QPixmap pxm(10,10);
        pxm.fill(graphSettings.color);
        item->setIcon(pxm);
    }
}

GraphData::~GraphData()
{
    graph->setVisible(false);
}

void GraphData::RefreshData()
{
    offset = 0.0;
    graph->setData(*time, this->value, true);

    max = -std::numeric_limits<double>::max();
    min = std::numeric_limits<double>::max();

    for (auto i : value)
    {
        if (i > max)
        {
            max = i + 0.001;
        }
        if (i < min)
        {
            min = i - 0.001;
        }
    }
}

void GraphData::PushBack(const double &value)
{
    this->value.push_back(value);
}

const QVector<double> &GraphData::GetValue() const
{
    return value;
}

void GraphData::ChangeOffSet(const double &value)
{
    if (this->value.size() != 0)
    {
        double difference = value - offset;
        for (auto i : this->value)
        {
            i += difference;
        }

        offset = value;
        graph->setData(*time, this->value, true);
    }
}

void GraphData::ClearOffSet()
{
    ChangeOffSet(0.0);
}

void GraphData::Clear()
{
    value.clear();
    graph->setVisible(false);
    offset = 0.0;
}

void GraphData::ClearAll()
{
    value.clear();
    graph->setVisible(false);
    offset = 0.0;
    coloumnFile = 0;
}

bool GraphData::IsVisible() const
{
    return graph->visible();
}

QCPGraph * GraphData::GetGraph()
{
    return graph;
}

void GraphData::SetColor(const QColor &color)
{
    graph->setPen(QPen(color));
}

const QColor GraphData::GetColor() const
{
    return graph->pen().color();
}

int GraphData::GetColoumnFile()
{
    return coloumnFile;
}

void GraphData::SetColoumnFile(int value)
{
    coloumnFile = value;
}

double GraphData::getMax() const
{
    return max;
}

double GraphData::getMin() const
{
    return min;
}

void GraphData::itemChanged(QListWidgetItem *item)
{
    if (item != widgetItem)
        return;

    if (IsVisible())
    {
        qDebug() << "UnChecked";
        item->setIcon(QIcon());
        Clear();
        emit GraphIsVisible(item->text());
    }
    else
    {
        qDebug() << "Checked";
        QPixmap pxm(10,10);
        pxm.fill(GetColor());
        item->setIcon(pxm);
        graph->setVisible(true);
        emit GraphIsVisible(item->text());
    }
}

}
